package com.avic.rong.userOrder.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.telephony.PhoneNumberUtils;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.avic.pickerview.OptionsPickerView;
import com.avic.rong.BaseActivity;
import com.avic.rong.R;
import com.avic.rong.userOrder.event.InformUpdate;
import com.avic.rong.userOrder.api.AddAddressApi;
import com.avic.rong.userOrder.api.DeleteAddressApi;
import com.avic.rong.userOrder.api.UpdateAddressApi;
import com.avic.rong.userOrder.bean.AddressListBean;
import com.avic.rong.userOrder.bean.AddressShowBean;
import com.avic.rong.userOrder.bean.ZipCodeBean;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.DialogCustom;
import com.avic.rong.utils.ToastTools;
import com.example.minato.minastore.BaseResultEntity;
import com.example.minato.minastore.http.HttpManager;
import com.example.minato.minastore.listener.HttpOnNextListener;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;

public class UpdateAddressActivity extends BaseActivity {

    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.ll_address_select)
    LinearLayout llAddressSelect;
    @BindView(R.id.iv_default_address_select)
    ImageView ivDefaultAddressSelect;
    @BindView(R.id.tv_submit_save)
    TextView tv_submit_save;
    @BindView(R.id.et_user_name)
    EditText etUserName;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.et_detail_address)
    EditText etDetailAddress;

    @BindView(R.id.ll_default_address_select)
    LinearLayout ll_default_address_select;

    private String belongProvince;
    private String belongProvinceZipcode;
    private String belongCity;
    private String belongCityZipcode;
    private String belongCounty;
    private String belongArea;


    private Boolean DEFAULT_SELECT = false;
    private Intent intent;
    private OptionsPickerView<String> mOpv;
    private JSONObject mJsonObj;

    // 省数据集合
    private ArrayList<String> mListProvince = new ArrayList<String>();
    private ArrayList<ZipCodeBean> mListProvinceBean = new ArrayList<>();
    // 市数据集合
    private ArrayList<ArrayList<String>> mListCity = new ArrayList<ArrayList<String>>();
    private ArrayList<ArrayList<ZipCodeBean>> mListCityBean = new ArrayList<ArrayList<ZipCodeBean>>();
    // 区数据集合
    private ArrayList<ArrayList<ArrayList<String>>> mListArea = new ArrayList<ArrayList<ArrayList<String>>>();
    private ArrayList<ArrayList<ArrayList<ZipCodeBean>>> mListAreaBean = new ArrayList<ArrayList<ArrayList<ZipCodeBean>>>();
    private int address;
    private AddressListBean address_bean;

    private boolean isChange = false;
    private int province = 0;
    private int city = 0;
    private String intentType;

    private boolean iSubmitClick=true;

    private int isAddressList;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_update_address;
    }

    @Override
    protected void initView() {
        intent = getIntent();
        address = intent.getIntExtra("address", 0);
        intentType = intent.getStringExtra("intentType");

        selectAddress();

        if (intent != null && address != 0) {
            if (address == 1) {
                tvTitle.setText("新增收货地址");
                isAddressList = intent.getIntExtra("isAddressList" , -1);
                if (isAddressList != -1 && isAddressList > 0) {
                    ivDefaultAddressSelect.setSelected(false);
                } else {
                    ivDefaultAddressSelect.setSelected(true);
                }

            } else {
                //编辑地址页Title左侧增加“删除”按钮。（如果是默认地址，则不显示“删除”按钮）
                tvTitle.setText("编辑收货地址");
                tvRight.setText("删除");
                if ((AddressListBean) intent.getSerializableExtra("address_bean") != null) {
                    address_bean = (AddressListBean) intent.getSerializableExtra("address_bean");
                    etUserName.setText(address_bean.getConsignee());
                    etPhone.setText(address_bean.getTel());
                    tvAddress.setText(address_bean.getProvinceName() + address_bean.getCityName());
                    etDetailAddress.setText(address_bean.getAddress());
                    if (address_bean.getIsDefault() == 1) {
                        DEFAULT_SELECT = true;
                        ivDefaultAddressSelect.setSelected(DEFAULT_SELECT);
                        tvRight.setVisibility(View.GONE);
                    } else {
                        DEFAULT_SELECT = false;
                        ivDefaultAddressSelect.setSelected(DEFAULT_SELECT);
                        tvRight.setVisibility(View.VISIBLE);
                    }
                }


                if (mListProvinceBean!=null&&mListProvinceBean.size()>0&&address_bean!=null){
                    for (int i = 0; i < mListProvinceBean.size(); i++) {
                        if (mListProvinceBean.get(i).getZipcode().equals(address_bean.getProvince()+"")){
                            province=i;
                        }
                    }
                }
                if (mListCityBean!=null&&mListCityBean.size()>0&&address_bean!=null){
                    for (int i = 0; i < mListCityBean.size(); i++) {
                        ArrayList<ZipCodeBean> zipCodeBeans = mListCityBean.get(i);
                        for (int i1 = 0; i1 < zipCodeBeans.size(); i1++) {
                            if (zipCodeBeans.get(i1).getZipcode().equals(address_bean.getCity()+"")){
                                city=i1;
                            }
                        }
                    }
                }

            }
        } else {
            finish();
        }


        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isChange) {
                    DialogCustom.showDoubleDialog(UpdateAddressActivity.this, "", "修改的信息还未保存，确认现在返回吗？", "取消", "确定", new DialogCustom.CustomDialogDouble() {
                        @Override
                        public void rightButtonClicked() {

                            finish();
                        }

                        @Override
                        public void leftButtonClicked() {

                        }
                    });
                } else {
                    finish();
                }
            }
        });
        etUserName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                isChange = true;
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        etPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                isChange = true;
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        etDetailAddress.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                isChange = true;
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        tvAddress.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                isChange = true;
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });


    }

    private void selectAddress() {
        // 初始化Json对象
        initJsonData();
        // 初始化Json数据
        initJsonDatas();
        // 创建选项选择器对象
        mOpv = new OptionsPickerView<>(UpdateAddressActivity.this);

        // 设置标题
        mOpv.setTitle("选择城市");

        // 设置三级联动效果
        mOpv.setPicker(mListProvince, mListCity, mListArea, true);
        // 设置是否循环滚动
        mOpv.setCyclic(false, false, false);
//                if (address_bean!=null){
//                    // 设置默认选中的三级项目
//                    mOpv.setSelectOptions(address_bean.getProvince(), address_bean.getCity(), 0);
//                }else {


//                }


        // 监听确定选择按钮
        mOpv.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3) {
                province = options1;
                city = option2;
                // 返回的分别是三个级别的选中位置
                String addressStr = mListProvinceBean.get(options1).getName();
                belongProvince = mListProvinceBean.get(options1).getName();
                belongCity = mListCityBean.get(options1).get(option2).getName();
                belongProvinceZipcode = mListProvinceBean.get(options1).getZipcode();
                belongCityZipcode = mListCityBean.get(options1).get(option2).getZipcode();
                tvAddress.setText(belongProvince + belongCity);
                tvAddress.setTextColor(getResources().getColor(R.color.base_title_color));
            }
        });
    }

    private void saveSubmit() {
        String userName = etUserName.getText().toString().trim();
        String phone = etPhone.getText().toString().trim();
        String selectAddress = tvAddress.getText().toString().trim();
        String detailAddress = etDetailAddress.getText().toString().trim();
        if (TextUtils.isEmpty(userName)) {
            ToastTools.showToast(this, "请输入姓名");
            return;
        } else if (TextUtils.isEmpty(phone)) {
            ToastTools.showToast(this, "请输入手机号");
            return;
        }/* else if (!isPhoneNumber(phone)) {
            ToastTools.showToast(this, "手机号格式不正确");
            return;
        }*/ else if (selectAddress.equals("请选择地区")) {
            ToastTools.showToast(this, "请选择所在地区");
            return;
        } else if (TextUtils.isEmpty(detailAddress)) {
            ToastTools.showToast(this, "请输入详细地址");
            return;
        }
        if (!getSharedPreferencesUtil().getLogintoken().isEmpty()) {


            Map<String, String> paramBody = new HashMap<>();
            paramBody.put("token", getSharedPreferencesUtil().getLogintoken());
            paramBody.put("consignee", userName);
            paramBody.put("tel", phone);

            paramBody.put("address", detailAddress);
            //是否设置为默认收货地址 0：否 1：是
            if (DEFAULT_SELECT) {
                paramBody.put("isDefault", 1 + "");
            } else {
                paramBody.put("isDefault", 0 + "");
            }
            if (intent != null && address != 0) {
                if (address == 2) {
                    if (belongProvince != null) {
                        paramBody.put("provinceName", belongProvince);
                        paramBody.put("cityName", belongCity);
                        paramBody.put("province", belongProvinceZipcode + "");
                        paramBody.put("city", belongCityZipcode + "");
                    } else {
                        paramBody.put("provinceName", address_bean.getProvinceName());
                        paramBody.put("cityName", address_bean.getCityName());
                        paramBody.put("province", address_bean.getProvince() + "");
                        paramBody.put("city", address_bean.getCity() + "");
                    }
                    paramBody.put("addressId", address_bean.getAddressId() + "");
                } else {
                    paramBody.put("provinceName", belongProvince);
                    paramBody.put("cityName", belongCity);
                    paramBody.put("province", belongProvinceZipcode + "");
                    paramBody.put("city", belongCityZipcode + "");
                }
            }
            if (iSubmitClick){
                //只可以点击一次
                iSubmitClick=false;

                if (intent != null && address != 0) {
                    if (address == 1) {
                        final AddAddressApi addAddressApi = new AddAddressApi(this, simpleOnNextListener);
                        addAddressApi.setMap(paramBody);
                        addAddressApi.setCache(false);
                        HttpManager.getInstance().doHttpDeal(addAddressApi);
                    } else {
                        UpdateAddressApi updateAddressApi = new UpdateAddressApi(this, simpleOnNextListener);
                        updateAddressApi.setMap(paramBody);
                        updateAddressApi.setCache(false);
                        HttpManager.getInstance().doHttpDeal(updateAddressApi);
                    }
                } else {
                    finish();
                }
            }



        }
    }


    //删除地址
    HttpOnNextListener simpleOnNextListenerDealAddress = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                ToastTools.showToast(context, subjects.getMsg());
                return;
            }
            InformUpdate informUpdate = new InformUpdate();
            informUpdate.setEventType(informUpdate.ADD_ADDRESS_INFORM);
            EventBus.getDefault().post(informUpdate);
            finish();

        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {

        }
    };

    HttpOnNextListener simpleOnNextListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                ToastTools.showToast(UpdateAddressActivity.this, subjects.getMsg());
                return;
            }
            if (address == 1) {
                ToastTools.showToast(UpdateAddressActivity.this, "添加成功");
            } else {
                ToastTools.showToast(UpdateAddressActivity.this, "修改成功");
            }
            Object addressId = (Object) subjects.getData();

            //地址回显，并且返回到订单确认页
            String userName = etUserName.getText().toString().trim();
            String phone = etPhone.getText().toString().trim();
            String selectAddress = tvAddress.getText().toString().trim();
            String detailAddress = etDetailAddress.getText().toString().trim();
            AddressShowBean addressShowBean = new AddressShowBean();
            addressShowBean.setName(userName);
            addressShowBean.setAddress(selectAddress + detailAddress);
            addressShowBean.setPhone(phone);
            addressShowBean.setAddressId(addressId + "");

            InformUpdate informUpdate = new InformUpdate();
            informUpdate.setEventType(informUpdate.ADD_ADDRESS_INFORM);
            EventBus.getDefault().post(informUpdate);

            if (address == 1) {
                if (!TextUtils.isEmpty(intentType) && intentType.equals("order")) {
                    //如果从确认订单页进入并且为添加地址
                    //添加地址跳订单页的ID是接口返的，不需要从新赋值
                    Intent intent = new Intent(UpdateAddressActivity.this, OrderConfirmActivity.class);
                    intent.putExtra("addressShow", addressShowBean);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    startActivity(intent);
                } else {
                    //不是从确认订单页进入并且为添加地址
                    finish();
                }
            } else {
                if (!TextUtils.isEmpty(intentType) && intentType.equals("order")){
                    //如果从确认订单页进入并且为修改地址
                    //修改地址跳订单页的ID是从地址列表页传的，所以需要从新赋值
                    addressShowBean.setAddressId(address_bean.getAddressId()+"");

                    Intent intent = new Intent(UpdateAddressActivity.this, OrderConfirmActivity.class);
                    intent.putExtra("addressShow", addressShowBean);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    startActivity(intent);
                }else {
                    finish();
                }

            }


        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {

        }
    };

    @Override
    protected void addListener() {
        //地区选择
        llAddressSelect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
                // 隐藏软键盘
                imm.hideSoftInputFromWindow(((Activity)context).getWindow().getDecorView().getWindowToken(), 0);
                mOpv.setSelectOptions(province, city, 0);
                mOpv.show();
            }
        });

        //默认地址编辑地址时，默认地址按钮不能取消
        if (address == 1) {
            //默认地址选择
            ll_default_address_select.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //如何为添加地址  并且用户没有收货地址时  默认地址为选中状态不可点击
                    if (isAddressList != -1 && isAddressList == 0) {
                        if (ivDefaultAddressSelect.isSelected()){
                            return;
                        }

                    }


                    DEFAULT_SELECT = !DEFAULT_SELECT;
                    ivDefaultAddressSelect.setSelected(DEFAULT_SELECT);
                }
            });
        } else {
            if (address_bean.getIsDefault() != 1) {
                //默认地址选择
                ll_default_address_select.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        DEFAULT_SELECT = !DEFAULT_SELECT;
                        ivDefaultAddressSelect.setSelected(DEFAULT_SELECT);
                    }
                });
            }
        }
        //保存提交
        tv_submit_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveSubmit();


            }
        });

        //编辑页删除按钮
        tvRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogCustom.showDoubleDialog(UpdateAddressActivity.this, "", "是否确认删除？", "取消", "确定", new DialogCustom.CustomDialogDouble() {
                    @Override
                    public void rightButtonClicked() {
                        dealAddress();

                    }

                    @Override
                    public void leftButtonClicked() {

                    }
                });
            }
        });

    }

    private void dealAddress() {
        final DeleteAddressApi deleteAddressApi = new DeleteAddressApi(this, simpleOnNextListenerDealAddress);
        deleteAddressApi.setAddressId(address_bean.getAddressId() + "");
        deleteAddressApi.setCache(false);
        HttpManager.getInstance().doHttpDeal(deleteAddressApi);
    }

    /**
     * 从assert文件夹中读取省市区的json文件，然后转化为json对象
     */
    private void initJsonData() {
        try {
            StringBuffer sb = new StringBuffer();
            InputStream is = getAssets().open("city.json");
            int len = -1;
            byte[] buf = new byte[2048];
            while ((len = is.read(buf)) != -1) {
                sb.append(new String(buf, 0, len, "UTF-8"));
            }
            is.close();
            mJsonObj = new JSONObject(sb.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化Json数据，并释放Json对象
     */
    private void initJsonDatas() {
        try {
            JSONObject rootObj = mJsonObj.optJSONObject("root");
            JSONArray jsonArray = rootObj.optJSONArray("province");
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonP = jsonArray.getJSONObject(i);// 获取每个省的Json对象
                String province = jsonP.optString("name");
                ZipCodeBean provinceBean = new ZipCodeBean(jsonP.optString("name"), jsonP.optString("zipcode"));

                ArrayList<String> options2Items_01 = new ArrayList<String>();
                ArrayList<ArrayList<String>> options3Items_01 = new ArrayList<ArrayList<String>>();
                ArrayList<ZipCodeBean> options2Items_01_bean = new ArrayList<ZipCodeBean>();
                ArrayList<ArrayList<ZipCodeBean>> options3Items_01_bean = new ArrayList<ArrayList<ZipCodeBean>>();
                JSONArray jsonCs = jsonP.getJSONArray("city");
                for (int j = 0; j < jsonCs.length(); j++) {
                    JSONObject jsonC = jsonCs.getJSONObject(j);// 获取每个市的Json对象
                    String city = jsonC.optString("name");
                    ZipCodeBean cityBean = new ZipCodeBean(jsonC.optString("name"), jsonC.optString("zipcode"));
                    options2Items_01.add(city);// 添加市数据
                    options2Items_01_bean.add(cityBean);

                    ArrayList<String> options3Items_01_01 = new ArrayList<String>();
                    ArrayList<ZipCodeBean> options3Items_01_01_bean = new ArrayList<ZipCodeBean>();
                    JSONArray jsonAs = jsonC.optJSONArray("district");
                    if (jsonAs != null) {
                        for (int k = 0; k < jsonAs.length(); k++) {
                            JSONObject distObj = jsonAs.getJSONObject(k);
                            String district = distObj.optString("name");
                            ZipCodeBean districtBean = new ZipCodeBean(distObj.optString("name"), distObj.optString("zipcode"));
                            options3Items_01_01.add(district);// 添加区数据
                            options3Items_01_01_bean.add(districtBean);
                        }
                    }
                    options3Items_01.add(options3Items_01_01);
                    options3Items_01_bean.add(options3Items_01_01_bean);
                }
                mListProvince.add(province);// 添加省数据
                mListCity.add(options2Items_01);
                mListArea.add(options3Items_01);

                mListProvinceBean.add(provinceBean);
                mListCityBean.add(options2Items_01_bean);
                mListAreaBean.add(options3Items_01_bean);

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        mJsonObj = null;
    }

    /**
     * 判断手机号是否符合规范
     *
     * @param phoneNo 输入的手机号
     * @return
     */
    public static boolean isPhoneNumber(String phoneNo) {
        if (TextUtils.isEmpty(phoneNo)) {
            return false;
        }
        if (phoneNo.length() == 11) {
            for (int i = 0; i < 11; i++) {
                if (!PhoneNumberUtils.isISODigit(phoneNo.charAt(i))) {
                    return false;
                }
            }
            Pattern p = Pattern.compile("^((13[^4,\\D])" + "|(134[^9,\\D])" +
                    "|(14[5,7])" +
                    "|(15[^4,\\D])" +
                    "|(17[3,6-8])" +
                    "|(18[0-9]))\\d{8}$");
            Matcher m = p.matcher(phoneNo);
            return m.matches();
        }
        return false;
    }

}
